package com.hc.kotlin_coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity_Kotlin"
    val mainScope = MainScope()//构建协程作用域
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val tv_btn1 = findViewById<TextView>(R.id.tv_btn1)
        tv_btn1.text = "Hello World"
        val tv_btn2 = findViewById<TextView>(R.id.tv_btn2)
        tv_btn2.text = "Button"
        tv_btn2.setOnClickListener{
            Log.d(TAG,"tv_btn2_onClick")
            doSomething()
        }
    }

    fun doSomething(){
        mainScope.launch {
            delay(5000L)
            Log.d(TAG,"Coroutine is finish")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mainScope.cancel()
    }
}